import React, { useEffect, Fragment } from 'react';
import { Icon, Tooltip, Divider, Row, Col, Button } from 'antd';
import { connect } from 'dva';
import {
  Form,
  FormItem,
  createFormActions,
  FormEffectHooks,
  InternalFieldList as FieldList,
} from '@formily/antd';
import { Input, Switch, Range, Select, NumberPicker } from '@formily/antd-components';
import classNames from 'classnames';
import throttle from 'lodash/throttle';
import omit from 'lodash/omit';
import has from 'lodash/has';
import get from 'lodash/get';
import { getStepMarks } from '../utils';
import styles from '../../styles.less';

const actions = createFormActions();

const { onFormInputChange$ } = FormEffectHooks;

function ForComboModal({ dispatch, current, columnNum }) {
  useEffect(() => {
    // 清空状态
    actions.reset({ validate: false });

    // 剔除holder是冗余的key
    const keys = Object.keys(actions.getFormGraph()).filter(val => val !== '');

    // 遍历，给所有的formItem设置值
    keys.forEach(value => {
      if (has(current, value)) {
        actions.setFieldValue([value], get(current, value));
      }
    });
  }, [current]);

  return (
    <Form
      className={classNames(styles.configForm)}
      actions={actions}
      colon={false}
      effects={() => {
        // 只监控人工操作引起的FormItem值变化
        onFormInputChange$().subscribe(
          throttle(
            async () => {
              await actions.validate({ silent: true });
              // actions.getFormState().valid取到的结果是异步的，所以必须用到await actions.validate才能得到精确的结果
              const isValid = actions.getFormState().valid;

              // 校验失败
              if (!isValid) {
                return;
              }

              // 当前面板所有formitem字段的值
              let formValues = actions.getFormState().values;

              // 必填, 补充whitespace等字段
              if (get(formValues, 'rules.requiredRule.required') === true) {
                formValues = {
                  ...formValues,
                  rules: {
                    ...formValues.rules,
                    requiredRule: { required: true, whitespace: true, message: '必填项' },
                  },
                };
              }

              // required==false时剔除，（因为在reset()时 required会变成false）
              if (get(formValues, 'rules.requiredRule.required') === false) {
                formValues = {
                  ...formValues,
                  rules: omit(formValues.rules, ['requiredRule']),
                };
              }

              dispatch({
                type: 'formDesigner/updateNode',
                payload: formValues,
              });
            },
            300,
            { trailing: true, leading: false }
          )
        );
      }}
    >
      <FormItem
        label="标题"
        name="label"
        allowClear
        required
        triggerType="onChange"
        component={Input}
        placeholder="无"
        initialValue="_" // 避免在reset时触发校验
      />

      <FormItem
        label="字段名称"
        name="name"
        allowClear
        required
        disabled
        triggerType="onChange"
        component={Input}
        initialValue="_" // 避免在reset时触发校验
      />

      <FormItem
        label={
          <>
            水平跨度
            <Tooltip title="1表示占满一行">
              <Icon type="info-circle" className={styles.helpIcon} />
            </Tooltip>
          </>
        }
        style={{ width: '150px' }}
        name="megaProps.span"
        triggerType="onChange"
        min={1}
        step={1}
        max={columnNum}
        marks={getStepMarks(columnNum)}
        component={Range}
        initialValue={1}
      />

      <FormItem
        label="禁用"
        name="disabled"
        triggerType="onChange"
        component={Switch}
        initialValue={false}
      />

      <FormItem
        label="编辑"
        name="editable"
        triggerType="onChange"
        component={Switch}
        initialValue
      />

      <FormItem
        label="显示"
        name="display"
        triggerType="onChange"
        component={Switch}
        initialValue
      />

      <FormItem
        label="必填"
        name="rules.requiredRule.required"
        triggerType="onChange"
        component={Switch}
        initialValue={false}
      />

      <Divider style={{ fontSize: 14 }}>表格属性</Divider>
      <FormItem label="多选" name="tableProps.multiple" triggerType="onChange" component={Switch} />
      <FormItem
        label="请求地址"
        name="tableProps.url"
        triggerType="onChange"
        component={Input}
        rules={[{ required: true, whitespace: true, message: '必填项' }]}
      />
      <FormItem
        label="请求类型"
        initialValue="post"
        required
        name="tableProps.method"
        triggerType="onChange"
        component={Select}
        dataSource={[
          { label: 'post', value: 'post' },
          { label: 'get', value: 'get' },
          { label: 'put', value: 'put' },
        ]}
      />

      <FormItem
        label={
          <>
            rowKey
            <Tooltip title="使用 rowKey 指定表格 dataSource 的主键">
              <Icon type="info-circle" className={styles.helpIcon} />
            </Tooltip>
          </>
        }
        name="tableProps.rowKey"
        triggerType="onChange"
        component={Input}
        rules={[{ required: true, whitespace: true, message: '必填项' }]}
      />

      <FormItem
        label={
          <>
            label
            <Tooltip title="指定dataSource中的哪个字段用于显示">
              <Icon type="info-circle" className={styles.helpIcon} />
            </Tooltip>
          </>
        }
        name="tableProps.label"
        triggerType="onChange"
        component={Input}
        rules={[{ required: true, whitespace: true, message: '必填项' }]}
      />

      <FieldList name="tableProps.columns">
        {({ state, mutators }) => {
          const onAdd = () => mutators.push();
          const onRemove = index => mutators.remove(index);
          return (
            <Fragment>
              {state.value.map((item, index) => (
                // eslint-disable-next-line react/no-array-index-key
                <Row gutter={4} key={index}>
                  <Col span={11}>
                    <FormItem
                      placeholder="列名"
                      name={`tableProps.columns.${index}.title`}
                      triggerType="onChange"
                      component={Input}
                    />
                  </Col>

                  <Col span={11}>
                    <FormItem
                      placeholder="字段"
                      name={`tableProps.columns.${index}.dataIndex`}
                      triggerType="onChange"
                      component={Input}
                    />
                  </Col>

                  <FormItem
                    display={false}
                    initialValue
                    name={`tableProps.columns.${index}.ellipsis`}
                    triggerType="onChange"
                    component={Switch}
                  />

                  <Col span={2} className="text-right">
                    <Icon
                      type="close-circle"
                      className={styles.delCol}
                      onClick={() => {
                        onRemove(index);

                        // dispatch({
                        //   type: 'formDesigner/updateNode',
                        //   payload: update(current, {
                        //     tableProps: { columns: { $splice: [[index, 1]] } },
                        //   }),
                        // });
                      }}
                    />
                  </Col>
                </Row>
              ))}
              <Button className="margin-top" type="dashed" icon="plus" block onClick={onAdd}>
                增加一列
              </Button>
            </Fragment>
          );
        }}
      </FieldList>

      <FormItem
        label={
          <>
            过滤范围
            <Tooltip
              title="查询时按指定字段过滤
            "
            >
              <Icon type="info-circle" className={styles.helpIcon} />
            </Tooltip>
          </>
        }
        name="tableProps.filterScope"
        triggerType="onChange"
        component={Input}
        placeholder="多个字段名以 , 隔开"
        rules={[{ required: true, whitespace: true, message: '必填项' }]}
      />

      <FormItem
        label="搜索框(placeholder)"
        name="tableProps.searchPlaceholder"
        triggerType="onChange"
        component={Input}
        placeholder="无"
      />

      <Divider style={{ fontSize: 14 }}>弹窗属性</Divider>

      <FormItem
        label="弹窗标题"
        name="modalProps.title"
        triggerType="onChange"
        component={Input}
        placeholder="无"
      />

      <FormItem
        label="弹窗宽度"
        name="modalProps.width"
        triggerType="onChange"
        component={NumberPicker}
        formatter={value => `${value} px`}
        parser={value => value.replace(' px', '')}
      />
    </Form>
  );
}

export default connect(({ formDesigner }) => ({
  current: formDesigner.current,
  columnNum: formDesigner.columnNum,
}))(ForComboModal);
